package com.bw.lib_core.mvvm.view;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ViewDataBinding;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.blankj.utilcode.util.LogUtils;
import com.bw.lib_core.bean.BaseBean;
import com.bw.lib_core.bean.ErrorBean;
import com.bw.lib_core.bean.UIBusBean;
import com.bw.lib_core.bus.ActivityParams;
import com.bw.lib_core.mvvm.model.BaseModel;
import com.bw.lib_core.mvvm.viewmodel.BaseViewModel;
import com.bw.lib_core.mvvm.viewmodel.DefViewModel;

import java.lang.ref.WeakReference;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class BaseActivity<V extends ViewDataBinding, VM extends BaseViewModel> extends AppCompatActivity implements IView, View.OnClickListener {

    protected V mDataBinding;
    protected VM mViewModel;
    private UIObserver uiObserver;
    protected Bundle bundle;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initBinding();
        initViewModel();
        initBar();
        initParam();
        initObserver();
    }


    public void initBinding() {
        if (bandingLayout() != 0) {
            mDataBinding = DataBindingUtil.setContentView(this, bandingLayout());
        }
    }

    /**
     * ViewModel创建
     * mDataBinding和生命周期管理
     * ViewModel生命周期管理
     * ViewModel 和  DataBinding 关联
     */

    public void initViewModel() {
        //ViewModel 初始化
        if (mViewModel == null) {
            //反射调用 ->
            Class<VM> modelClass;
            Type type = getClass().getGenericSuperclass();
            if (type instanceof ParameterizedType) {
                modelClass = (Class<VM>) ((ParameterizedType) type).getActualTypeArguments()[1];
            } else {
                modelClass = (Class<VM>) DefViewModel.class;
            }
            mViewModel = createViewModel(modelClass);
        }
        //ViewModel 和  DataBinding 关联
        if (mDataBinding == null) {
            return;
        }
        if (initVariableId() != 0) {
            mDataBinding.setVariable(initVariableId(), mViewModel);
        }
        //mDataBinding和生命周期管理
        mDataBinding.setLifecycleOwner(this);
        //ViewModel生命周期管理
        getLifecycle().addObserver(mViewModel);
        //关联UILiveData
        uiObserver = new UIObserver(this);
        mViewModel.getLiveData().observe(this, uiObserver);
    }

    /**
     * 创建ViewModel
     */
    private VM createViewModel(Class<VM> modelClass) {
        return new ViewModelProvider(this, new ViewModelProvider.NewInstanceFactory()).get(modelClass);
    }

    @Override
    public void initParam() {
        if (!getIntent().hasExtra("bundle")) {
            return;
        }
        bundle = getIntent().getBundleExtra("bundle");
    }

    @Override
    public void initBar() {

    }

    @Override
    public void initObserver() {

    }

    @Override
    public void startPage(Class<?> aClass) {
        startActivity(new Intent(this, aClass));
    }

    @Override
    public void startPage(Class<?> aClass, Bundle bundle) {
        Intent intent = new Intent(this, aClass);
        intent.putExtra("bundle", bundle);
        startActivity(intent);
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showError(ErrorBean bean) {

    }

    @Override
    public void hideError() {

    }

    @Override
    public void onClick(View v) {

    }

    /**
     * UI层操作统一入口
     */
    public static class UIObserver implements Observer<UIBusBean> {
        /**
         * 弱引用
         */
        private WeakReference<BaseActivity> weakReference;

        public UIObserver(BaseActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void onChanged(UIBusBean s) {
            if (weakReference.get() == null) {
                return;
            }
            switch (s.action) {
                case START_PAGE:
                    Class<?> c = (Class<?>) s.data.get(ActivityParams.CLASS_KEY);
                    weakReference.get().startPage(c);
                    break;
                case START_PAGE_BUNDLE:
                    Class<?> pClass = (Class<?>) s.data.get(ActivityParams.CLASS_KEY);
                    Bundle bundle = (Bundle) s.data.get(ActivityParams.BUNDLE_KEY);
                    weakReference.get().startPage(pClass, bundle);
                    break;
                case SHOW_LOADING:
                    weakReference.get().showLoading();
                    break;
                case HIDE_LOADING:
                    weakReference.get().hideLoading();
                    break;
                case SHOW_ERROR:
                    ErrorBean errorBean = (ErrorBean) s.data.get(ActivityParams.ERROR_KEY);
                    assert errorBean != null;
                    LogUtils.e(errorBean.message);
                    weakReference.get().showError(errorBean);
                    break;
                case HIDE_ERROR:
                    weakReference.get().hideError();
                    break;
                case FINISH_PAGE:
                    weakReference.get().finish();
                    break;
            }
        }
    }
}
